package com.jzo2o.market.handler;

import com.jzo2o.common.utils.DateUtils;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Component
@Slf4j
public class XxlJobHandler {

    @Resource
    private SyncManager syncManager;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponService couponService;

    /**
     * 活动状态修改，
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     * 1分钟一次
     */

    @XxlJob("updateActivityStatus")
    public void updateActivitySatus(){
        LocalDateTime now = DateUtils.now();
        try {
              activityService.lambdaUpdate()
                    .ge(Activity::getDistributeEndTime, now)
                    .le(Activity::getDistributeStartTime, now)
                    .eq(Activity::getStatus, ActivityStatusEnum.NO_DISTRIBUTE.getStatus())
                    .set(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                    .update();
        } catch (Exception e) {
            log.error("活动状态修改为进行中失败");

        }

        try {
            activityService.lambdaUpdate()
                  .lt(Activity::getDistributeEndTime, now)
                  .eq(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                  .set(Activity::getStatus, ActivityStatusEnum.LOSE_EFFICACY.getStatus())
                  .update();
        } catch (Exception e) {
            log.error("活动状态修改为已失效失败---");
        }

        log.info("活动状态修改成功");
    }

    /**
     * 已领取优惠券自动过期任务
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {
        try {
             couponService.lambdaUpdate()
                    .lt(Coupon::getValidityTime, DateUtils.now())
                    .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus())
                    .set(Coupon::getStatus, CouponStatusEnum.INVALID.getStatus())
                    .update();
        } catch (Exception e) {
            log.error("优惠券状态修改为已失效失败");
        }

        log.info("优惠券状态修改成功");
    }


}
